import React, {useCallback, useEffect, useMemo, useState} from "react"
import {Pageable} from "../../utils/Page";
import {
    createProcurementSupplier,
    queryProcurementSuppliers,
    QueryProcurementSuppliersResponse,
    updateProcurementSupplier
} from "../../apis/ProcurementSupplierApi";
import AuthorizationResource from "../../components/AuthorizationResource";
import {Button, ConfigProvider, Form, Input, Select, Table, Transfer} from "antd";
import {EditOutlined, PlusOutlined} from "@ant-design/icons";
import {
    AntdTableColumnRenders,
    castFilterValue,
    mergePaginationAndPageable,
    useTableSearchTextColumnProps
} from "../../utils/AntdTableUtils";
import {QueryGoodsResponse} from "../../apis/GoodsApi";
import DataPageLayout from "../../components/DataPageLayout";
import FormDrawer from "../../components/FormDrawer";
import {useNavigate} from "react-router";
import {observerDashboardPageWrapper} from "./ObserverDashboardPageWrapper";
import {createDirectSaleOrder} from "../../apis/DirectSaleOrderApi";
import {NumberIdAndName} from "../../types/BasicModels";
import {getAllGoodsBrand, GoodsBrandSummary} from "../../apis/GoodsBrandsApi";

export interface pageProps {

}

export interface ProcurementSupplierFormData {
    name: string
}

const ProcurementSupplierPage: React.FC<pageProps> = () => {
    const [openAddDrawer, setOpenAddDrawer] = useState(false)
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryProcurementSuppliersResponse[]>([])
    const [searchNameText, setSearchNameText] = useState<string>()
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)


    const [editingItemId, setEditingItemId] = useState<number>()
    const editingItem = useMemo(() => {
        return data.find(it => it.id === editingItemId)
    }, [editingItemId, data]);

    let query = useCallback(() => {
        setLoading(true)
        queryProcurementSuppliers({name: searchNameText,}, pageable).then(response => {
            setTotalElements(response.data.totalElements)
            setData(response.data.content)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), searchNameText,]);

    useEffect(() => {
        query()
    }, [query]);
    let nameSearchProps = useTableSearchTextColumnProps<QueryGoodsResponse>("name", {
        placeholder: "名称"
    });

    // const [brands, setBrands] = useState<GoodsBrandSummary[]>([]);
    // useEffect(() => {
    //     getAllGoodsBrand().then(value => setBrands(value.data))
    // }, []);
    // const [selectedBrandIds, setSelectedBrandIds] = useState<number[]>([])
    // useEffect(() => {
    //     setSelectedBrandIds(editingItem?.excludeBrands?.map(it => it.id) ?? [])
    // }, [editingItem]);


    function buildFormItems() {
        return <>
            <Form.Item label={"名称"} name="name" rules={[{required: true}]}>
                <Input/>
            </Form.Item>

        </>
    }

    let navigate = useNavigate();

    return <>
        <DataPageLayout rightActions={<AuthorizationResource authorities={["采购_供货商_新增"]}>
            <Button type={"primary"} onClick={() => {
                setOpenAddDrawer(true)
            }}><PlusOutlined/>新增采购供货商</Button>
        </AuthorizationResource>}>
            <ConfigProvider componentSize={"small"}>
                <Table loading={loading} dataSource={data} rowKey={"id"} pagination={{
                    current: pageable.page,
                    pageSize: pageable.size,
                    total: totalElements,
                }} onRow={(data, index) => {
                    return {
                        onClick: () => {
                            navigate(`procurements/suppliers/${data.id}`)
                        }
                    }
                }} onChange={(pagination, filters, sorter) => {
                    setSearchNameText(castFilterValue(filters.name))
                    setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                }}>
                    <Table.Column dataIndex={"name"} title={"名称"} {...nameSearchProps}/>
                    <Table.Column dataIndex={"amount"} title={"订单数量"} {...nameSearchProps}/>
                    <Table.Column dataIndex={"lastOrderSubmittedDateTime"}
                                  title={"最后一次采购时间"}
                                  render={AntdTableColumnRenders.dateTimeColumnRender}/>
                    <Table.Column<QueryProcurementSuppliersResponse> title={"操作"} render={(_, item) => {
                        return <>
                            <AuthorizationResource authorities={[]}>
                                <Button type={"link"} onClick={() => {
                                    createDirectSaleOrder(item.id).then(response => {
                                        navigate(`/directSales/orders/${response.data}`)
                                    })
                                }}>下单</Button>
                            </AuthorizationResource>
                            <AuthorizationResource authorities={["采购_供货商_修改"]}><Button type={"link"}
                                                                                              onClick={() => {
                                                                                                  setEditingItemId(item.id)
                                                                                              }}>
                                <EditOutlined/>
                                修改
                            </Button>
                            </AuthorizationResource>
                            <AuthorizationResource authorities={["采购_账目_查询"]}>
                                <Button type={"link"}
                                        href={`/#/procurements/suppliers/${item.id}/paymentRecords`}>账目</Button>
                            </AuthorizationResource>
                        </>
                    }}/>
                </Table>
            </ConfigProvider>
        </DataPageLayout>
        <FormDrawer<ProcurementSupplierFormData> onClose={() => setOpenAddDrawer(false)}
                                                 title={"新增供货商"}
                                                 onConfirm={async (values) => {
                                                     return createProcurementSupplier({...values}).then(() => {
                                                         setOpenAddDrawer(false)
                                                         query()
                                                     })
                                                 }}
                                                 open={openAddDrawer}>
            {buildFormItems()}
        </FormDrawer>
        <FormDrawer<ProcurementSupplierFormData> open={!!editingItem} title={"修改采购供货商"} onClose={() => {
            setEditingItemId(undefined)
        }} onConfirm={async (values) => {
            return updateProcurementSupplier(editingItemId!!, {...values}).then(() => {
                query()
                setEditingItemId(undefined)
            })
        }} initialValues={editingItem ? {
            name: editingItem.name ?? "",
        } : undefined}>
            {buildFormItems()}
        </FormDrawer>
    </>
}


export default observerDashboardPageWrapper(ProcurementSupplierPage, "procurements/suppliers", "采购供货商")
